class ServiceAddressModel {
  // API base url
  List<String> apiBaseUrls;
  int apiBaseUrlIndex;

  String? get apiBaseUrl {
    if (apiBaseUrlIndex < 0 || apiBaseUrlIndex >= apiBaseUrls.length) {
      return null;
    }
    return apiBaseUrls[apiBaseUrlIndex];
  }

  set apiBaseUrl(String? value) {
    if (value == null || value.isEmpty) {
      return;
    }

    int index = apiBaseUrls.indexWhere((element) => element == value);
    if (index != -1) {
      apiBaseUrlIndex = index;
    } else {
      apiBaseUrls.insert(0, value);
      apiBaseUrlIndex = 0;
    }
  }

  // H5 base url
  List<String> h5BaseUrls;
  int h5BaseUrlIndex;

  String? get h5BaseUrl {
    if (h5BaseUrlIndex < 0 || h5BaseUrlIndex >= h5BaseUrls.length) {
      return null;
    }
    return h5BaseUrls[h5BaseUrlIndex];
  }

  set h5BaseUrl(String? value) {
    if (value == null || value.isEmpty) {
      return;
    }

    int index = h5BaseUrls.indexWhere((element) => element == value);
    if (index != -1) {
      h5BaseUrlIndex = index;
    } else {
      h5BaseUrls.insert(0, value);
      h5BaseUrlIndex = 0;
    }
  }

  // WebSocket url
  List<String> webSocketUrls;
  int webSocketUrlIndex;

  String? get webSocketUrl {
    if (webSocketUrlIndex < 0 || webSocketUrlIndex >= webSocketUrls.length) {
      return null;
    }
    return webSocketUrls[webSocketUrlIndex];
  }

  set webSocketUrl(String? value) {
    if (value == null || value.isEmpty) {
      return;
    }

    int index = webSocketUrls.indexWhere((element) => element == value);
    if (index != -1) {
      webSocketUrlIndex = index;
    } else {
      webSocketUrls.insert(0, value);
      webSocketUrlIndex = 0;
    }
  }

  ServiceAddressModel({
    required this.apiBaseUrls,
    this.apiBaseUrlIndex = 0,
    required this.h5BaseUrls,
    this.h5BaseUrlIndex = 0,
    required this.webSocketUrls,
    this.webSocketUrlIndex = 0,
  });

  factory ServiceAddressModel.fromJson(Map<String, dynamic> json) {
    return ServiceAddressModel(
      apiBaseUrls: List<String>.from(json['apiBaseUrls']),
      apiBaseUrlIndex: json['apiBaseUrlIndex'] ?? 0,
      h5BaseUrls: List<String>.from(json['h5BaseUrls']),
      h5BaseUrlIndex: json['h5BaseUrlIndex'] ?? 0,
      webSocketUrls: List<String>.from(json['webSocketUrls']),
      webSocketUrlIndex: json['webSocketUrlIndex'] ?? 0,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'apiBaseUrls': apiBaseUrls,
      'apiBaseUrlIndex': apiBaseUrlIndex,
      'h5BaseUrls': h5BaseUrls,
      'h5BaseUrlIndex': h5BaseUrlIndex,
      'webSocketUrls': webSocketUrls,
      'webSocketUrlIndex': webSocketUrlIndex,
    };
  }
}
